package com.yang.provider.service.impl;

import com.yang.provider.entity.Order;
import com.yang.provider.mapper.OrderMapper;
import com.yang.provider.mapper.StockMapper;
import com.yang.provider.service.OrderService;
import com.yang.provider.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author ：YangRan
 * @date ：Created in 2021/11/24 14:27
 * @description：OrderServerImpl
 * @modified By：
 * @version: 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    /**
     * 库存service
     */
    @Resource
    private StockService stockService;


    /**
     * 订单order mapper
     */
    @Resource
    private OrderMapper orderMapper;


    @Resource
    private RedissonClient redissonClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createOrder(String userId, Integer productId) {
        /**  如果不加锁，必然超卖 **/
        RLock lock = redissonClient.getLock("stock:" + productId);
        try {
            lock.lock(10, TimeUnit.SECONDS);
            int stock = stockService.getOne(productId).getStockNum();
            log.info("剩余库存：{}", stock);
            if (stock <= 0) {
                return false;
            }
            String orderNo = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            /** 减库存操作 **/
            if (stockService.decrease(productId)) {
                Order order = new Order();
                order.setUserId(userId);
                order.setProductId(productId);
                order.setOrderNo(orderNo);
                Date now = new Date();
                order.setCreateTime(now);
                order.setUpdateTime(now);
                orderMapper.insert(order);
                return true;
            }
        } catch (Exception ex) {
            log.error("下单失败", ex);
        } finally {
            lock.unlock();
        }
        return false;
    }

    @Override
    public boolean createOrderWithoutRedisLock(String userId, Integer productId) {
        int stock = stockService.getOne(productId).getStockNum();
        log.info("剩余库存：{}", stock);
        if (stock <= 0) {
            return false;
        }
        String orderNo = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        /** 减库存操作 **/
        if (stockService.decrease(productId)) {
            Order order = new Order();
            order.setUserId(userId);
            order.setProductId(productId);
            order.setOrderNo(orderNo);
            Date now = new Date();
            order.setCreateTime(now);
            order.setUpdateTime(now);
            orderMapper.insert(order);
            return true;
        }
        return false;
    }


}

